<?php
header('Content-Type: text/html; charset=utf-8');
ini_set('memory_limit','500M');
define('ROOTPATH', dirname(dirname(dirname(dirname(__FILE__)))) . '/');
define('APPPATH', ROOTPATH . "application/");
define('BASEPATH', ROOTPATH . "/system/");
define('CONFIGPATH', APPPATH . "configs/");
set_time_limit(0);
$min = $_REQUEST['min'];
$length = $_REQUEST['length'];
$message = $_REQUEST['content'];
nlog($_REQUEST, $min);
//var_dump($message);
/***  连接数据库 Start  ***/
$db = connect_db();
$conn = $db->linkid;

if(!$conn)
{
	die('Could not connect: ' . mysql_error());
}

//查询数据
$sql="select token from tmp_token where status = 1 limit $min,$length;";
$result=mysql_query($sql,$conn);
if(!$result)
{
	die($sql.mysql_error(). "mysql_query Failed!");
}
$i = 0;
$count = 0;
$deviceTokenArray=array();
while($rows=mysql_fetch_array($result))
{
	$deviceTokenArray[]=$rows['token'];
}
nlog(array($min,$length), $min);
/***  连接数据库 End  ***/


// Put your alert message here:
$body['aps'] = array(
		'alert' => $message,
		'sound' => 'default'
);
//Create the payload body,Encode the payload as JSON
$payload = json_encode($body);
$fp = connect_apns();
$fpCount = 1;
echo 'Connected to APNS' . PHP_EOL;

//开始推送
foreach ($deviceTokenArray as $deviceToken)
{
	$star = get_microtime();
	// Build the binary notification
	$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
	// Send it to the server
	$b1 = get_microtime();
	$result = fwrite($fp, $msg, strlen($msg));
	$b = get_microtime() - $b1;
	nlog(array('con',$b), $min);
	if (!$result)
	{
		fclose($fp);
		echo 'Message not delivered' . PHP_EOL;
		if (++$fpCount > 150) {
			die('connect too much!');
		}
		else {
			$fp = connect_apns();
		}
	}
	else
	{
		echo 'Message successfully delivered' . PHP_EOL;
		//推送成功改写数据库
		$a1 = get_microtime();
		$sql="UPDATE `tmp_token` SET `status` = '2' WHERE `token` = "."'".$deviceToken."';";
		$result=mysql_query($sql,$conn);
		$a = get_microtime() - $a1;
		nlog(array('sql',$a), $min);
		echo 'result = '.$result.PHP_EOL;
		if(!$result)
		{
			echo "mysql_query Failed!";
		}
	}
	$time = get_microtime() - $star;
	nlog(array($time,$fpCount,$result), $min);
}

echo 'All token have Push!';

mysql_close($conn);

function connect_apns()
{
	// Put your private key's passphrase here:
	$passphrase = '123456';
	////////////////////////////////////////////////////////////////////////////////
	$ctx = stream_context_create();
	stream_context_set_option($ctx, 'ssl', 'local_cert', dirname(__FILE__).'/apansdk-dev.pem');
	//stream_context_set_option($ctx, 'ssl', 'local_cert', 'apans-dis.pem');
	stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
	
	// Open a connection to the APNS server
	$fp = stream_socket_client(
			'ssl://gateway.push.apple.com:2195', $err,
			$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
	if (!$fp)
		exit("Failed to connect: $err $errstr" . PHP_EOL);	
	return $fp;
}

function nlog($data, $filename) {
	return ;
	if (is_array($data)) {
		$log = date("Y-m-d H:i:s") . " " . http_build_query($data) . "\r\n";
	} else {
		$log = date("Y-m-d H:i:s") . " " . $data . "\r\n";
	}
	$path = dirname(__FILE__) .'/'. $filename .date("Y-m-d"). ".txt";
	file_put_contents($path, $log, FILE_APPEND);
}

function get_microtime()
{
	list($usec, $sec) = explode(' ', microtime());
	return ((float)$usec + (float)$sec);
	//return microtime(true);
}

function connect_db() {
	include_once CONFIGPATH.'db.php';
	include_once BASEPATH.'libraries/database.php';
	$db = new Database($config['db']);
	return $db;
}

?>